clear;
warning off;
current = pwd;

%一些参数
ask_rotate = 'n';%生成图像是否要旋转
ask_rotate_num = 90;
color_flag = 0;

%raw_dir:包含MRI影像的文件夹地址，并以"*.nii"结尾。
raw_dir = 
%affined_dir:同上
affined_dir = 
%save_dir 输出图片的文件夹
save_dir = 

% 需要采集无意义数据的数量
sample_count = 10;

mkdir(save_dir);
cd(save_dir);
mkdir('raw')
mkdir('affined')
mkdir('temp_raw');
mkdir('temp_aff');
raw_Files = dir(raw_dir);
raw_LengthFiles = length(raw_Files);
aff_Files = dir(affined_dir);
aff_Files_Lenth = length(aff_Files);
% 检查文件列表长度是否相同。
if(raw_LengthFiles ~= aff_Files_Lenth)
    disp("文件长度不同！检查文件名称是否对应！");
    disp("文件长度不同！检查文件名称是否对应！");
end
for i = 1:aff_Files_Lenth
    raw_file_name = raw_Files(i).name;
    raw_file_dir  = fullfile(raw_Files(i).folder,raw_Files(i).name);
    raw_image = niftiread(raw_file_dir);
    raw_image_info = niftiinfo(raw_file_dir);
    raw_nifti_array = size(raw_image);
    raw_image = permute(raw_image, [1 3 2]);

    aff_file_name= aff_Files(i).name;
    aff_file_dir = fullfile(aff_Files(i).folder,aff_Files(i).name);
    aff_image = niftiread(aff_file_dir);
    aff_image_info = niftiinfo(aff_file_dir);
    aff_nifti_array = size(aff_image);
    aff_image = permute(aff_image, [1 3 2]); 
    
    if length(raw_nifti_array) == 3
       %if grayscale required
       if color_flag == 0
           % Create output folder
           %mkdir(ask_output)
           % Get Vols and Slice
           raw_total_slices = raw_nifti_array(3);
           aff_total_slices = aff_nifti_array(3);
           disp('Converting NIfTI to png, please wait...')
           aff_area_max = 0;
           slice_max = 0;
           slice_counter = 0;
            % Iterate Through Slices
           current_slice = 1;
            while current_slice <= raw_total_slices
                % Alternate Slices
                if mod(slice_counter, 1) == 0     

                    % Rotate images if selected
                    if lower(ask_rotate) == 'y'
                        if ask_rotate_num == 90
                            raw_data = rot90(mat2gray(raw_image(:,:,current_slice)));
                            aff_data = rot90(mat2gray(aff_image(:,:,current_slice)));
                        elseif ask_rotate_num == 180
                            raw_data = rot90(rot90(mat2gray(raw_image(:,:,current_slice))));
                            aff_data = rot90(rot90(mat2gray(aff_image(:,:,current_slice))));
                        elseif ask_rotate_num == 270
                            raw_data = rot90(rot90(rot90(mat2gray(raw_image(:,:,current_slice)))));
                            aff_data = rot90(rot90(rot90(mat2gray(aff_image(:,:,current_slice)))));
                        end
                    elseif lower(ask_rotate) == 'n'
                    disp('OK, I will convert it as it is.');
                    raw_data = mat2gray(raw_image(:,:,current_slice));
                    aff_data = mat2gray(aff_image(:,:,current_slice));
                    end
                    raw_data(256,256) = 0; 
                    aff_data(256,256) = 0; 
                    aff_area = bwarea(aff_data);
                    if(aff_area>aff_area_max)
                        aff_area_max = aff_area;
                        slice_max = current_slice;
                    end
                    % Set Filename as per slice and vol info
                    raw_filename =  erase(raw_Files(i).name, '.nii') + "_Z"+ num2str(sprintf('%03d', current_slice)) + ".png";
                    aff_filename =  erase(raw_Files(i).name, '.nii') + "_Z"+ num2str(sprintf('%03d', current_slice)) + ".png";
                    % Write Image
                    mkdir(save_dir + "\temp_raw")
                    cd(save_dir + "\temp_raw");
                    imwrite(raw_data, char(raw_filename));
                    mkdir(save_dir + "\temp_aff")
                    cd(save_dir + "\temp_aff");
                    imwrite(aff_data, char(aff_filename));
                    slice_counter = slice_counter + 1;
                    percentage = strcat('Please wait. Converting...', ' ', num2str((current_slice/raw_total_slices)*100), '% Complete');

                    if ((current_slice/raw_total_slices)*100) == 100
                        disp('100% Complete! Images successfully converted');
                    else
                        disp(percentage);
                    end                    
                end
                current_slice  = current_slice  + 1;
            end
            aff_png_temp_dir = save_dir+'\temp_aff';
            cd(aff_png_temp_dir);
            aff_png_temp_dir = save_dir+'\temp_aff\*.png';
            aff_Files_png = dir(aff_png_temp_dir);
            aff_Files_Lenth = length(aff_Files_png);

            aff_png_dir = save_dir+'\affined';
            mkdir(aff_png_dir);
            
            slice_sample = randsample(176,sample_count);
            
            for j = 1:sample_count
                move_file_name = aff_Files_png(slice_sample(j)).name;
                movefile(char(move_file_name),aff_png_dir);        
            end
            for j = (slice_max-5):(slice_max+5)
                
                if( exist(fullfile(aff_Files_png(j).folder,aff_Files_png(j).name) ,"file") ~= 0)
                  move_file_name = aff_Files_png(j).name;
                  movefile(char(move_file_name),aff_png_dir);
                end
            end
            delete *.png;
            raw_png_temp_dir = save_dir+'\temp_raw';
            mkdir(raw_png_temp_dir)
            cd(raw_png_temp_dir);
            raw_png_temp_dir = save_dir+'\temp_raw\*.png';
            raw_Files_png = dir(raw_png_temp_dir);
            raw_LengthFiles = length(raw_Files_png);

            raw_png_dir = save_dir+'\raw';
            mkdir(raw_png_dir);
            for j = 1:sample_count
                move_file_name = raw_Files_png(slice_sample(j)).name;
                movefile(char(move_file_name),raw_png_dir);        
            end
            for j = (slice_max-5):(slice_max+5)
                
                if( exist(fullfile(raw_Files_png(j).folder,raw_Files_png(j).name) ,"file") ~= 0)
                  move_file_name = raw_Files_png(j).name;
                  movefile(char(move_file_name),raw_png_dir);
                end
            end
            delete *.png;         
   elseif length(nifti_array) ~= 3 || 4
            disp('NIfTI must be 3D or 4D. Please try again.');
        end
    end
    cd(save_dir);
end
rmdir("temp_aff");
rmdir("temp_raw");

